package cc.linker.steplink.crm.task;

import cc.linker.steplink.crm.commons.lock.RedisLock;
import cc.linker.steplink.crm.merchant.service.acs.XbMerchantService;
import cc.linker.steplink.crm.merchanth5.dao.acs.MerchantWalletDao;
import cc.linker.steplink.crm.merchanth5.dao.acs.WithdrawTaskDao;
import cc.linker.steplink.crm.merchanth5.pojo.WithdrawTaskPo;
import cc.linker.steplink.crm.merchanth5.service.acs.MerchantWalletService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: CKQ
 * @DateTime: 2020/5/26 13:33
 * @Description: TODO
 */
@Slf4j
@Component
@Async
public class WithdrawTask {
    @Autowired
    private WithdrawTaskDao withdrawTaskDao;

    @Autowired
    private MerchantWalletService merchantWalletService;

    @Autowired
    private XbMerchantService xbMerchantService;

    @RedisLock(value = "withdrawTaskRun")
    @Scheduled(cron = "0 15 7,12,17 * * ?")
    public void withdrawTaskRun() {
        WithdrawTaskPo withdrawTaskPo = new WithdrawTaskPo();
        //获取待执行的提现任务
        List<WithdrawTaskPo> withdrawList = withdrawTaskDao.getAwaitWithdrawList();
        if (withdrawList.size() > 0) {
            withdrawList.forEach(po -> {
                //调用提现接口，返回提现接口调用是否成功
                Integer status = 0;
                Map<String, Object> billWithdrawMap = new HashMap<>();
                if (!StringUtils.isEmpty(po.billMapJson)) {
                    billWithdrawMap = (Map) JSON.parse(po.billMapJson);
                }
                if (po.source == 1) {
                    LOGGER.info("WithdrawTask-withdrawTaskRun：开始提现---------------------：" + JSON.toJSONString(po));
                    status = merchantWalletService.sendWithdaw(po, billWithdrawMap, true) ? 1 : 2;
                } else {
                    status = xbMerchantService.sendWithdaw(billWithdrawMap, po, true) ? 1 : 2;
                }
                //提现后修改任务状态
                if (withdrawTaskDao.updateWithdrawTaskStatus(po.withdrawId, status) > 0) {
                    LOGGER.info("WithdrawTask-withdrawTaskRun：提现成功，提现单号：" + po.withdrawCode);
                }
            });
        } else {
            LOGGER.info("WithdrawTask-withdrawTaskRun：未查询到需要执行的提现操作！");
        }
    }
}
